package csu.web.mypetstore.controller;

import csu.web.mypetstore.domain.*;

import csu.web.mypetstore.pojo.*;
import csu.web.mypetstore.service.*;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class OtherController {
    @Autowired
    private ProductService productService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ItemService itemService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private CartService cartService;


    @GetMapping("getCategoryInfo")
    @ResponseBody
    @Transactional
    public String getCategoryInfo(@RequestParam("categoryId") String categoryId) {
        try {
            List<Product> products = productService.getProductListByCategory(categoryId);

            // 构建HTML内容
            StringBuilder htmlContent = new StringBuilder("<ul>");
            for (Product product : products) {
                htmlContent.append("<li>")
                        .append("<b>").append(product.getName()).append("</b><br>")
                        .append(product.getDescn())
                        .append("</li>");
            }
            htmlContent.append("</ul>");

            return htmlContent.toString();
        } catch (Exception e) {
            e.printStackTrace(); // 建议使用日志框架记录异常
            return "无法获取产品信息，请稍后再试。";
        }
    }
    @GetMapping("code")
    public void generateCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        // 创建验证码对象
        Captcha captcha = new Captcha();

        // 生成验证码并存入Session
        String code = captcha.generate();
        session.setAttribute("code", code);

        // 生成验证码图片
        Image image = captcha.generate(code);

        // 设置响应内容类型为图片
        response.setContentType("image/jpeg");

        // 禁用缓存（可选，根据需求调整）
        ImageIO.setUseCache(false);

        // 输出图片到响应流
        try (OutputStream out = response.getOutputStream()) {
            ImageIO.write((RenderedImage) image, "JPEG", out);
        }
    }
    @RequestMapping("searchProduct")
    @ResponseBody
    @Transactional
    public String searchProducts(@RequestParam("keyword") String keyword) {
        List<Product> productList = productService.searchProductList(keyword);

        // 使用 Stream API 将产品名称连接为逗号分隔的字符串
        return productList.stream()
                .map(Product::getName)
                .collect(Collectors.joining(","));
    }
    @PostMapping("search")
    @Transactional
    public ModelAndView searchProducts(@RequestParam("keyword") String keyword,
                                       HttpSession session) {
        List<Product> productList = productService.searchProductList(keyword);

        if (!productList.isEmpty()) {
            Product product = productList.get(0);
            List<Item> itemList = itemService.getItemListByProduct(product.getProductid());

            session.setAttribute("product", product);
            session.setAttribute("itemList", itemList);

            return new ModelAndView("catalog/product");
        } else {
            ModelAndView mav = new ModelAndView("catalog/search");
            mav.addObject("signOnMsg", "没有找到相似的商品");
            return mav;
        }
    }
    @PostMapping("newOrder")
    @Transactional
    public String processOrder(
            @RequestParam(value = "newOrderFormSubmitted", required = false) String newOrderFormSubmitted,
            @RequestParam(value = "shipAddressSubmitted", required = false) String shipAddressSubmitted,
            @RequestParam(value = "confirmed", required = false) String confirmed,
            @RequestParam(value = "cardType", required = false) String cardType,
            @RequestParam(value = "creditCard", required = false) String creditCard,
            @RequestParam(value = "expiryDate", required = false) String expiryDate,
            @RequestParam(value = "billToFirstName", required = false) String billToFirstName,
            @RequestParam(value = "billToLastName", required = false) String billToLastName,
            @RequestParam(value = "billAddress1", required = false) String billAddress1,
            @RequestParam(value = "billAddress2", required = false) String billAddress2,
            @RequestParam(value = "billCity", required = false) String billCity,
            @RequestParam(value = "billState", required = false) String billState,
            @RequestParam(value = "billZip", required = false) String billZip,
            @RequestParam(value = "billCountry", required = false) String billCountry,
            @RequestParam(value = "courier", required = false) String courier,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "shipToFirstName", required = false) String shipToFirstName,
            @RequestParam(value = "shipToLastName", required = false) String shipToLastName,
            @RequestParam(value = "shipAddress1", required = false) String shipAddress1,
            @RequestParam(value = "shipAddress2", required = false) String shipAddress2,
            @RequestParam(value = "shipCity", required = false) String shipCity,
            @RequestParam(value = "shipState", required = false) String shipState,
            @RequestParam(value = "shipZip", required = false) String shipZip,
            @RequestParam(value = "shipCountry", required = false) String shipCountry,
            HttpSession session) {

        Account loginAccount = (Account) session.getAttribute("loginAccount");
        String username = (loginAccount != null) ? loginAccount.getUsername() : null;

        if (newOrderFormSubmitted != null) {

            System.out.println("--------------------newOrderFormSubmitted--------------------");
            Orders order = new Orders();
            Date date = new Date();
            order.setOrderdate(date);

            Cart cart = (Cart) session.getAttribute("cart");
            Iterator<CartItem> cartItems = cart.getCartItems();
            List<LineItem> lineItems = new ArrayList<>();
            BigDecimal total = BigDecimal.ZERO;

            while (cartItems.hasNext()) {
                CartItem cartItem = cartItems.next();
                LineItem lineItem = new LineItem();
                lineItem.setUnitprice(String.valueOf(cartItem.getItem().getListprice()));
                lineItem.setQuantity(String.valueOf(cartItem.getQuantity()));
                lineItem.setItem(cartItem.getItem());

                total = total.add(lineItem.getTotal());
                lineItems.add(lineItem);
            }

            try {
                List<Orders>ordersList=ordersService.queryAllOrders();



                // order.setOrderid(Integer.valueOf(ordersList.size()+1) );

            } catch (Exception e) {
                e.printStackTrace(); // 建议使用日志框架记录异常
                throw new RuntimeException("Failed to generate order ID", e);
            }

            order.setTotalprice(total.doubleValue());
            order.setLineItems(lineItems);
            order.setUserid(username);
            order.setCardtype(cardType);
            order.setCreditcard(creditCard);
            order.setExprdate(expiryDate);
            order.setBilltofirstname(loginAccount.getFirstname());
            order.setBilltolastname(loginAccount.getLastname());
            order.setBilladdr1(loginAccount.getAddr1());
            order.setBilladdr2(loginAccount.getAddr2());
            order.setBillcity(loginAccount.getCity());
            order.setBillstate(loginAccount.getState());
            order.setBillzip(loginAccount.getZip()==null?1:loginAccount.getZip());
            order.setBillcountry(loginAccount.getCountry());
            order.setCourier(courier);
            order.setStatus(status);
            System.out.println("order.getBilltofirstname()="+order.getBilltofirstname());

            session.setAttribute("order", order);
            return "order/shipAddress"; // 返回配送地址页面
        }

        if (shipAddressSubmitted != null) {
            System.out.println("--------------------shipAddressSubmitted-------------------------");
            Orders order = (Orders) session.getAttribute("order");
            order.setUserid(username);
            order.setShiptofirstname("abc");
            order.setShiptolastname("abc");
            order.setShipaddr1("长沙市");
            order.setShipaddr2("岳阳市");
            order.setShipcity("长沙市");
            order.setShipstate("岳阳市");
            order.setShipzip(Integer.valueOf(shipZip==null?"1":shipZip));
            order.setShipcountry("中国");
            order.setCourier(courier);
            order.setStatus(status);

            session.setAttribute("order", order);
            return "order/confirmOrder"; // 返回确认订单页面
        }

        if (confirmed != null) {

            System.out.println("--------------------confirmed----------------------------");
            Orders order = (Orders) session.getAttribute("order");

            // 输出待插入的数据（调试用）
            System.out.println("Inserting Order Data:");
            System.out.println("Order ID: " + order.getOrderid());
            System.out.println("Userid: " + order.getUserid());
            System.out.println("Order Date: " + order.getOrderdate());
            System.out.println("Total Price: " + order.getTotalprice());
            System.out.println("Shipping Address: " + order.getShipaddr1() + ", " + order.getShipcity() + ", " + order.getShipstate() + ", " + order.getShipzip());
            System.out.println("Billing Address: " + order.getBilladdr1() + ", " + order.getBillcity() + ", " + order.getBillstate() + ", " + order.getBillzip());

            // 插入订单和订单状态到数据库
            try {




                cartService.deleteAllItem(username);
                ordersService.insertOrder(order);
                ordersService.insertOrderStatus(order);


                Cart cart = (Cart) session.getAttribute("cart");

                for (CartItem cartItem : cart.getItemList()) {

                    Item item = cartItem.getItem();

                    orderDetailService.insertOrderDetail(order.getOrderid(), item.getItemid(), cartItem.getQuantity(),loginAccount.getUsername());

                }
                cart.clear();
            } catch (Exception e) {
                e.printStackTrace(); // 建议使用日志框架记录异常
            }

            return "order/viewOrder"; // 返回查看订单页面
        }

        return "redirect:/mainForm"; // 默认重定向到主页面（若无任何条件匹配）
    }
}
